<script lang="ts" setup>
import { ref, onMounted, onBeforeUpdate } from 'vue'
import { Approver, ApproverConfig } from '@/types/modules/approver-config'
import { ApproverConfigDetail } from '@/types/modules/approver-config-detail'

import * as api from '@/api/modules/approver-config'

const props = defineProps({ 
  title: { type: String, default: () => 'Default Title' },
  itemData: {
    type: Array as PropType<ApproverConfig[]>,
    default: () => []
  }
})

const emit = defineEmits(['ok', 'refresh'])

const formRef = ref()
const refs = ref<any[]>([])
const formState = ref<ApproverConfig[]>(props.itemData)

const handleBasicOk = async () => {
  let valid = await formRef.value.validate().catch((err: any) => err)
  if (!valid?.errorFields?.length) return valid
  return false
}

const handleRelateArrOk = async () => {
  let relateArr = []
  let isFailed = false
  for (let i = 0; i < refs.value.length; i++) {
    const result = await (refs.value[i] as any).handleOk()
    relateArr.push(result)
    if (!result) {
      isFailed = true
    }
  }
  if (isFailed) return false
  return relateArr
}

const handleOk = async () => {
  const basicResult = await handleBasicOk()
  const relateArrRsult = await handleRelateArrOk()

  if (basicResult && relateArrRsult) {
    return formState
  }
  return false
}

onMounted(() => {
  approverSelectOptions()    
})

onBeforeUpdate(() => {
  refs.value = []

  formState.value = props.itemData  
})

const approverOptions = ref()

const approverSelectOptions = async () => {  
  const res = await api.getApproverList()
  if (res.status === 0) {
    approverOptions.value = res.data    
  }
}

const resetBasicForm = () => {
  formRef.value.resetFields()
}

const resetRelateArrForm = () => {
  for (let i = 0; i < refs.value.length; i++) {
    ; (refs.value[i] as any).resetForm()
  }
}

const resetForm = () => {
  resetBasicForm()
  resetRelateArrForm()
}

defineExpose({ handleOk, resetForm })
</script>

<template>
  <div>
    <a-form ref="formRef" :model="formState" :labelWrap="true">
      <h2>{{ props.title }}</h2>      
      <div v-for="biz in formState" :key="biz.key" class="bizSelector">        
        <span>{{ biz.name }}：</span>        
        <a-select v-model:value="biz.approverDetails" key="approver.id" style="width: 100%" :get-popup-container="(node: any) => node.parentNode"
          option-filter-prop="approver.name" placeholder="请选择" mode="multiple" show-arrow allow-clear @change="onChange">
          <a-select-option v-for="approver in approverOptions" :key="approver.id" :value="approver.id">
            <span>{{ approver.name }}</span>
          </a-select-option>
        </a-select>
      </div>      
      <a-button @click="emit('ok')">保存</a-button>
    </a-form>
  </div>
</template>

<style lang="less" scoped>
.ant-form > h2 {
  margin-bottom: 2rem;
}

.ant-form > .bizSelector {
  margin-bottom: 2px;
}

.ant-form > .ant-btn {
  margin-top: 5px;
}
</style>